package com.huifaapp.mall.activity.Homefragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.BaseActivity;


@SuppressLint({"NewApi"})
public class WebActivity extends BaseActivity {
    WebView xiangYueWebView;
    TextView webTitle, actionClose;
    View back;
    View webRefer;
    ProgressBar progressBar;
    boolean isNewWeb = false;


    public static final String IS_SHOW_MENU = "isShowMenu";

    // --

    /**
     * 指定打开的URL
     */
    public static final String EXTRA_URL = "url";

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        Intent intent = getIntent();
        String url = intent.getStringExtra(EXTRA_URL);
        String action = intent.getAction();

        xiangYueWebView = (WebView)findViewById(R.id.xiangYueWebView);
        webTitle = (TextView)findViewById(R.id.webTitle);
        webRefer = findViewById(R.id.webRefer);
        back = (View) findViewById(R.id.back);
        progressBar = (ProgressBar) findViewById(R.id.url_loading);//进度条
        actionClose = (TextView) findViewById(R.id.actionClose);

        isNewWeb = intent.getBooleanExtra("isNewWeb", false);
        if (url == null || url.equals("")) {
            showMsg("地址错误");
            return;
        }
        if (url.substring(0, 1).equals("w") || url.substring(0, 1).equals("W")) {
            url = "http://" + url;
        }
        debugInfo("url = " + url);

        if (isNewWeb) {
            actionClose.setVisibility(View.INVISIBLE);
        }

        WebSettings webSettings = xiangYueWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setUseWideViewPort(true); // 关键点
        webSettings.setAllowFileAccess(true); // 允许访问文件
        webSettings.setSupportZoom(true); // 支持缩放
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); // 不加载缓存内容

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        xiangYueWebView.getSettings().setUseWideViewPort(true);
        //xiangYueWebView.getSettings().setBuiltInZoomControls(true);

        //xiangYueWebView.addJavascriptInterface(new WebAppInterface(), "xyAndroid");
        //xiangYueWebView.addJavascriptInterface(new WebXyExternalInterface(), "xyExternal");

        xiangYueWebView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                debugError("shouldOverrideUrlLoading = " + url);
                Uri uri = Uri.parse(url);
                if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("ftp")) {
                    if (isNewWeb) {
                        Intent intent = new Intent(WebActivity.this, WebActivity.class);
                        intent.putExtra("url", url);
                        intent.putExtra("isNewWeb", true);
                        intent.putExtra(IS_SHOW_MENU, getIntent().getBooleanExtra(IS_SHOW_MENU, false));
                        startActivityForResult(intent, 100);
                    }
                    return false;
                } else {
					 /*try {
						 Intent intent1 = new Intent(Intent.ACTION_VIEW, uri);
						 startActivity(intent1);
					 } catch (Exception e) {}*/
                    return super.shouldOverrideUrlLoading(view, url);
                }
            }
            //网页加载失败时调用，隐藏加载提示旋转进度条
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                //showMsg("加载失败,请重试");
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                // 不要使用super，否则有些手机访问不了，因为包含了一条 handler.cancel()
                // super.onReceivedSslError(view, handler, error);
                // 接受所有网站的证书，忽略SSL错误，执行访问网页
                handler.proceed();
                //默认的处理方式，WebView变成空白页
                //handler.cancel();
                // 其他处理
                //handleMessage(Message msg);
            }
        });

		/*webRefer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				hideInputMethod();
				TtkShare ttkShare = (TtkShare) getIntent().getSerializableExtra("share");
				if (ttkShare == null) {
					return;
				}

				ShareMenu shareMenu = new ShareMenu(that);
				shareMenu.setTtkShare(ttkShare);
				shareMenu.create();
				shareMenu.show();
			}
		});*/

        if (getIntent().getBooleanExtra(IS_SHOW_MENU, false)) {
            webRefer.setVisibility(View.VISIBLE);
        }

        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (xiangYueWebView.canGoBack()) {
                    xiangYueWebView.goBack();
                } else {
                    finish();
                }
            }
        });

        actionClose.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        xiangYueWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                /**
                 * 网页进度条
                 */
                if (newProgress == 100) {
                    progressBar.setVisibility(View.GONE);
                    if (xiangYueWebView.canGoBack()) {
                        actionClose.setVisibility(View.INVISIBLE);
                    } else {
                        actionClose.setVisibility(View.INVISIBLE);
                    }
                } else {
                    progressBar.setVisibility(View.VISIBLE);
                    progressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                webTitle.setText("客服");
            }
        });

        xiangYueWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String arg1, String arg2,
                                        String arg3, long arg4) {
                Uri uri = Uri.parse(url);
                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(it);
            }
        });
        xiangYueWebView.loadUrl(url);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (xiangYueWebView != null) {
            xiangYueWebView.onResume();
        }
    }

    @Override
    protected void onDestroy() {
        if (xiangYueWebView != null) {
            ViewGroup parent = (ViewGroup) xiangYueWebView.getParent();
            if (parent != null) {
                parent.removeView(xiangYueWebView);
            }
            xiangYueWebView.removeAllViews();
            xiangYueWebView.destroy();
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (xiangYueWebView != null) {
            xiangYueWebView.onPause();
        }
    }



    @Override
    public void onBackPressed() {
        if (xiangYueWebView.canGoBack()) {
            xiangYueWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        super.onActivityResult(arg0, arg1, arg2);
        if (arg1 == 100) {
            setResult(100);
            finish();
        } else if (arg1 == 2 && arg2 != null) {

        }
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_web;
    }
    @Override
    protected void initialize() {}
    @Override
    protected void initView() {}
}
